<script setup>
import { ref, computed, onMounted } from 'vue'
//先从api里面导入方法
//import { artGetChannelsService, artDelChannelsService } from '@/api/article'
import { ChatDotSquare, Delete, Search, Picture } from '@element-plus/icons-vue'

//导入接口
import { getPostingApi, getPostingDetailApi, delPostingApi } from '@/service/api/posting/posting.ts'
const getPostingService = getPostingApi.getPosting
const getPostingDetailService = getPostingDetailApi.getPostingDetail
const delPostingService = delPostingApi.delPosting
//调用接口获取帖子列表数据并对数据做处理
const getPosting = async () => {
  try {
    const res = await getPostingService()
    const newData = res.data.map((item) => {
      // 将时间戳转换为日期对象
      const date = new Date(parseInt(item.createAt))

      // 格式化日期字符串
      const year = date.getFullYear()
      const month = ('0' + (date.getMonth() + 1)).slice(-2)
      const day = ('0' + date.getDate()).slice(-2)
      const hours = ('0' + date.getHours()).slice(-2)
      const minutes = ('0' + date.getMinutes()).slice(-2)
      const seconds = ('0' + date.getSeconds()).slice(-2)
      const formattedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`

      // 返回新的对象，替换原来的时间戳属性
      return {
        id: item.postId, //帖子id
        title: item.title, //帖子标题
        text: item.content, //帖子正文
        username: item.authorNickName, //发帖用户名
        date: formattedDate, //发帖日期
        img: item.images //发帖图片
      }
    })
    tableData.value = newData
  } catch (err) {
    console.log(err)
  }
}

//用于存储帖子列表的数据
const tableData = ref([
  // {
  //   id: 5961,
  //   title: '我的好兄弟',
  //   text: '心里有苦你对我说',
  //   date: '2022-07-10 14:53',
  //   username: '周帅',
  //   img: [],
  //   commentStatus: true
  // }
])

//帖子评论区
//获取帖子详情的数据
const getPostingDetail = async (id) => {
  try {
    const res = await getPostingDetailService({ postId: id })
    commentData.value = res.data.postDetail.comments
    //console.log(comments.value)
  } catch (err) {
    console.log(err)
  }
}

//展示评论区抽屉
const table = ref(false)
const showComment = (row) => {
  table.value = true
  getPostingDetail(row.id)
}

//评论数据
const commentData = ref([])
const loading = ref(false)

//分页
const pageSize = ref(10)
const currentPage = ref(1)
//实现方法：
const currentChange = (e) => {
  currentPage.value = e
}
const handleSizeChange = (val) => {
  console.log(val)
  pageSize.value = val
}

//分页函数
const postingList = computed(() => {
  let result = tableData.value.slice(
    (currentPage.value - 1) * pageSize.value,
    currentPage.value * pageSize.value
  )
  return result
})

//批量操作帖子
//获取选择的帖子
const multipleSelection = ref([])
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

//批量关闭评论区函数
const closeComments = () => {
  console.log(multipleSelection.value[0].commentStatus)
  ElMessageBox.confirm('你确定关闭选中的所有帖子的评论区？', '提醒：', {
    confirmButtonText: '确定关闭',
    cancelButtonText: '取消关闭',
    type: 'warning',
    center: true
  })
    .then(() => {
      //发请求更改commentStatus
      ElMessage({
        type: 'success',
        message: '关闭成功！'
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '关闭失败！'
      })
    })
}

//批量开启评论区函数
const openCommentsList = ref([])
const openComments = () => {
  openCommentsList.value = multipleSelection.value.map((item) => {
    return { postId: item.id }
  })
  console.log(openCommentsList.value)
  //发请求更改commentStatus
  ElMessage({
    type: 'success',
    message: '开启成功！'
  })
}

//批量删除函数
const deleteInBulk = () => {
  console.log(multipleSelection.value)
  ElMessageBox.confirm('你确定删除选中的所有帖子？', '提醒：', {
    confirmButtonText: '确定删除',
    cancelButtonText: '取消删除',
    type: 'warning',
    center: true
  })
    .then(() => {
      ElMessage({
        type: 'success',
        message: '删除成功！'
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '删除失败！'
      })
    })
}

//删除单个帖子
const onDelPosting = (row) => {
  //await artDelChannelsService(row.id) //删除选中行数据
  console.log(row.id)
  ElMessageBox.confirm('你确定删除该帖子？', '提醒：', {
    confirmButtonText: '确定删除',
    cancelButtonText: '取消删除',
    type: 'warning',
    center: true
  })
    .then(async () => {
      const res = await delPostingService({ postId: row.id })
      await getPosting() //刷新
      console.log(res)
      ElMessage({
        type: 'success',
        message: '删除成功！'
      })
    })

    .catch(() => {
      ElMessage({
        type: 'info',
        message: '删除失败！'
      })
    })
}

//删除单个评论
//const commentStatus = ref(false) //控制评论区状态
const onDelComment = (row) => {
  console.log(row)
  ElMessageBox.confirm('你确定删除该评论？', '提醒：', {
    confirmButtonText: '确定删除',
    cancelButtonText: '取消删除',
    type: 'warning',
    center: true
  })
    .then(() => {
      ElMessage({
        type: 'success',
        message: '删除成功！'
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '删除失败！'
      })
    })
}

//展示图片区抽屉
const srcList = ref([])
const pic = ref(false)
const showPic = (row) => {
  pic.value = true
  srcList.value = row.img
  if (srcList.value === null) {
    ElMessage.error('此帖子没有图片哦')
  }
}

//一进页面就加载数据
onMounted(() => {
  getPosting()
})
</script>

<template>
  <PageContainer>
    <el-header class="header">
      <div class="searchPlace">
        <div class="text"><span>帖子查询 :</span></div>
        <el-input
          v-model="searchInput"
          style="width: 240px"
          placeholder="请输入搜索关键词:帖子文字和用户"
          clearable
        />
        <el-button @click="search" type="primary">
          <span>
            <el-icon><Search /></el-icon>
          </span>
        </el-button>
        <el-button @click="search" type="success">重置搜索内容</el-button>
      </div>
      <div class="postingControl">
        <el-button @click="openComments" type="success">批量开启评论区</el-button>
        <el-button @click="closeComments" type="danger">批量关闭评论区</el-button>
        <el-button @click="deleteInBulk" type="danger">批量删除帖子</el-button>
      </div>
    </el-header>

    <el-main>
      <!-- 帖子数据展示 -->
      <el-table
        :data="postingList"
        empty-text="暂时没有数据哦~"
        v-loading="loading"
        @selection-change="handleSelectionChange"
        stripe
        ref="multipleTable"
      >
        <el-table-column type="selection" label="选中帖子" width="50" />
        <el-table-column label="帖子ID" type="index" width="100" />
        <el-table-column prop="date" label="发帖时间" />
        <el-table-column prop="username" label="发帖用户" />
        <el-table-column prop="text" label="帖子文字" />
        <el-table-column prop="pictures" label="帖子图片">
          <template #default="{ row }"
            ><!--#default它用于接收具名插槽的默认内容，这里使用解构,可以在插槽内部访问这些变量并进行相关操作。。-->
            <el-button
              :icon="Picture"
              circle
              plain
              type="primary"
              @click="showPic(row)"
            ></el-button>
            <!-- <el-button :icon="Check" circle plain></el-button> -->
          </template>
        </el-table-column>
        <el-table-column prop="commentStatus" label="帖子评论">
          <template #default="{ row }"
            ><!--#default它用于接收具名插槽的默认内容，这里使用解构,可以在插槽内部访问这些变量并进行相关操作。。-->
            <el-button
              :icon="ChatDotSquare"
              circle
              plain
              type="primary"
              @click="showComment(row)"
              :disabled="row.commentStatus"
            ></el-button>
          </template>
        </el-table-column>
        <el-table-column prop="choice" label="删除帖子">
          <template #default="{ row }"
            ><!--#default它用于接收具名插槽的默认内容，这里使用解构,可以在插槽内部访问这些变量并进行相关操作。。-->
            <el-button
              :icon="Delete"
              circle
              plain
              type="danger"
              @click="onDelPosting(row)"
            ></el-button>
            <!-- <el-button :icon="Check" circle plain></el-button> -->
          </template>
        </el-table-column>
      </el-table>

      <!-- 评论区抽屉 -->
      <el-drawer v-model="table" title="帖子评论区" direction="rtl" size="50%">
        <el-table :data="commentData" empty-text="暂时没有评论哦~">
          <el-table-column label="评论顺序" type="index" width="100" />
          <el-table-column property="studentNickName" label="评论用户" width="200" />
          <el-table-column property="content" label="评论内容" width="300" />
          <el-table-column prop="commentChoice" label="删除评论">
            <template #default="{ row }"
              ><!--#default它用于接收具名插槽的默认内容，这里使用解构,可以在插槽内部访问这些变量并进行相关操作。。-->
              <el-button
                :icon="Delete"
                circle
                plain
                type="danger"
                @click="onDelComment(row)"
              ></el-button>
              <!-- <el-button :icon="Check" circle plain></el-button> -->
            </template>
          </el-table-column>
        </el-table>
      </el-drawer>

      <!-- 图片区抽屉 -->
      <el-drawer v-model="pic" title="帖子图片" direction="rtl" size="42%">
        <el-row :gutter="20">
          <template #default>
            <el-card
              v-for="(url, index) in srcList"
              :key="index"
              class="pic"
              style="width: 190px; height: 190px"
            >
              <el-image
                style="width: 150px; height: 150px"
                :src="url"
                fit="cover"
                :preview-src-list="[`${url}`]"
              />
            </el-card>
          </template>
          <!-- <el-col :span="6"><div class="grid-content"></div></el-col>
          <el-col :span="6"><div class="grid-content"></div></el-col>
          <el-col :span="6"><div class="grid-content"></div></el-col> -->
        </el-row>
      </el-drawer>

      <!-- 分页部分 -->
      <div>
        <el-pagination
          layout="total,sizes,prev, pager, next"
          :total="tableData.length"
          :page-size="pageSize"
          @current-change="currentChange"
          @size-change="handleSizeChange"
          :page-sizes="[5, 10, 20, 50]"
          :current-page="currentPage"
        >
        </el-pagination>
      </div>
      <template #empty>
        <el-empty description="没有数据"></el-empty>
      </template>
    </el-main>
  </PageContainer>
</template>

<style lang="scss" scoped>
.header {
  background-color: white;
  display: flex;
  align-items: center;
  flex-wrap: nowrap;
  border-radius: 10px;
  width: 96.8%;
  background-color: #999;
  justify-content: space-between;
  margin-left: 1.6%;
  .text {
    flex-wrap: nowrap;
    background-color: #3f9eff;
    height: 68%;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 20%;
    border-radius: 5px 0 0 5px;
  }
  .searchPlace {
    flex-wrap: nowrap;
    display: flex;
    justify-content: center;
    align-items: center;
    width: 50%;
    //background-color: #999;
    height: 80%;
    border-radius: 15px;
  }
  .postingControl {
    flex-wrap: nowrap;
    display: flex;
  }
}

.pic {
  display: block;
}

.el-row {
  margin-bottom: 20px;
}
.el-row:last-child {
  margin-bottom: 0;
}
.el-col {
  border-radius: 4px;
}
</style>
